# 自定义分页组件
from django.utils.safestring import mark_safe
import copy

# 使用时在对应文件中添加如下组件

# path/view.py 中
# def xxx():
#     queryset = *.objects.all() # 查询数据
#     page_obj = Pagination(request, queryset)
#     content = {
#         "queryset": page_obj.page_queryset,
#         "page_string": page_obj.html(),
#     }
#   return render(request, "path/.html", content)

# "path/.html" 中 分页
# <div class="clearfix">
#     <ul class="pagination">
#         {{page_string}}
#     </ul>
# </div>


class Pagination(object):
    # queryset 查询的数据
    # page_param = "page" 获取当前页码数
    # page_size=10 每页展示数
    # plus=5 页码数条
    def __init__(self, request, queryset, page_param="page", page_size=10, plus=5):
        # import copy
        query_dict = copy.deepcopy(request.GET)
        query_dict.__mutable = True
        self.query_dict = query_dict

        # 总页码计数
        total_count = queryset.count()

        self.page_param = page_param

        # 每页展示条目数
        self.page_size = page_size

        # 取商与余数
        total_page_count, div = divmod(total_count, page_size)
        if div:
            # 余数不为 0 时总页码数加 1
            total_page_count += 1
        self.total_page_count = total_page_count

        # 获取当前页码数
        # 方法一
        page = request.GET.get(page_param, "1")
        if page.isdecimal():
            page = int(page)
            if page > total_page_count:
                page = total_page_count
        else:
            page = 1
        # # 方法二
        # try:
        #     page = int(request.GET.get(page_param,'1'))
        #     if page > total_page_count:
        #         page = total_page_count
        #     elif page < 1:
        #         page = 1
        # except:
        #     page = 1

        # 当前页码
        self.page = page

        # 起始页码
        self.start = (page - 1) * page_size
        # 结束页码
        self.end = page * page_size

        # 依据页码提取的展示数据
        self.page_queryset = queryset[self.start : self.end]

        self.plus = plus

    def html(self):
        # 总页码数小于等于 两倍 plus + 1 （11）时，限制页码数起始为 1，并显示所以页码。
        if self.total_page_count <= 2 * self.plus + 1:
            start_page = 1
            end_page = self.total_page_count
        else:
            # 当前页码小于等于 plus（5） 时。限制页码数起始为 1
            if self.page <= self.plus:
                start_page = 1
                end_page = 2 * self.plus + 1
            else:
                # 当前页码加上plus 大于总页码数时。限制页码数显示 不超过 总页码数
                if self.page + self.plus > self.total_page_count:
                    start_page = self.total_page_count - 2 * self.plus
                    end_page = self.total_page_count
                # 其他情况，页码条 显示当前页码左右plus的页码数
                else:
                    start_page = self.page - self.plus
                    end_page = self.page + self.plus

        # 页码
        page_str_list = []

        self.query_dict.setlist(self.page_param, [1])
        # 首页
        page_str_list.append(
            '<li><a href="?{}">首 页</a></li>'.format(self.query_dict.urlencode())
        )
        # 上一页
        if self.page > 1:
            self.query_dict.setlist(self.page_param, [self.page - 1])
            prev = '<li><a href="?{}">上一页</a></li>'.format(
                self.query_dict.urlencode()
            )
        else:
            self.query_dict.setlist(self.page_param, [1])
            prev = '<li><a href="?{}">上一页</a></li>'.format(
                self.query_dict.urlencode()
            )
        page_str_list.append(prev)

        for i in range(start_page, end_page + 1):
            self.query_dict.setlist(self.page_param, [i])
            if i == self.page:
                ele = '<li class="active"><a href="?{}">{}</a></li>'.format(
                    self.query_dict.urlencode(), i
                )
            else:
                ele = '<li><a href="?{}">{}</a></li>'.format(
                    self.query_dict.urlencode(), i
                )
            page_str_list.append(ele)

        # 下一页
        if self.page < self.total_page_count:
            self.query_dict.setlist(self.page_param, [self.page + 1])

            next = '<li><a href="?{}">下一页</a></li>'.format(
                self.query_dict.urlencode()
            )
        else:
            self.query_dict.setlist(self.page_param, [self.total_page_count])
            next = '<li><a href="?{}">下一页</a></li>'.format(
                self.query_dict.urlencode()
            )
        page_str_list.append(next)

        # 尾页
        self.query_dict.setlist(self.page_param, [self.total_page_count])
        page_str_list.append(
            '<li><a href="?{}">尾 页</a></li>'.format(self.query_dict.urlencode())
        )
        search_string = """
            <li>
                <form style="float: left;margin-left: -1px" method="get">
                    <input name="page"
                            style="position: relative;float:left;display: inline-block;width: 80px;border-radius: 0;"
                            type="text" class="form-control" placeholder="页码">
                    <button style="border-radius: 0" class="btn btn-default" type="submit">跳转</button>
                </form>
            </li>
            """
        page_str_list.append(search_string)

        # from django.utils.safestring import mark_safe
        page_string = mark_safe("".join(page_str_list))

        return page_string
